/**
 * request 网络请求工具
 * 更详细的 api 文档: https://github.com/umijs/umi-request
 */
import { extend } from 'umi-request';
import db from './localstorage';
const ingoreUrl = ['/cube/login', '/cube/venueInfo/queryVenueInfoListByUserId', '/cube/venueInfo/list', '/cube/venueInfo/queryVenueInfoById', '/cube/file/deleteManyImg','/cube/file/uploadManyImg','/cube/file/preContractQRCode','/cube/sys/user/batchRemove'];

const errorHandler = error => {
  const { response } = error;
  if (response.status == '504' || response.status == '403') {
    window.location.href = '/user/login'
  }
  return response;
};
/**
 * 配置request请求时的默认参数
 */

const request = extend({
  prefix: "/cube",
  errorHandler,
  // 默认错误处理
  credentials: 'include', // 默认请求是否带上cookie
});

request.interceptors.response.use((response, options) => {
  if (response.headers.get('Content-Type').indexOf('application/vnd.ms-excel') > -1) {
    response.blob().then((blob) => {
      const a = window.document.createElement('a');
      const downUrl = window.URL.createObjectURL(blob);// 获取 blob 本地文件连接 (blob 为纯二进制对象，不能够直接保存到磁盘上)
      const filename = response.headers.get('content-disposition').split('fileName=')[1].split('.');
      a.href = downUrl;
      a.download = `${decodeURI(filename[0])}.${filename[1]}`;
      a.click();
      window.URL.revokeObjectURL(downUrl);
    })
  }
  return response;
});

request.interceptors.request.use((url, options) => {
  let requestBody = {
    url: `${url}`,
    options,
  }
  if (!ingoreUrl.includes(url)) {
    requestBody.options['headers'] = { venueId: db.get("venue").id}
  }
  return requestBody;
})
export default request;
